package com.smsc.headend.task.engine.handler.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.smsc.headend.common.enums.errorcode.TaskHandlerErrorCode;
import com.smsc.headend.module.data.enums.OperationGroup;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.protocol.cosem.bo.CosemData;
import com.smsc.headend.module.protocol.cosem.enums.Unit;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.CosemXmlService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author liangli
 * @date 2020/9/16
 */
public class ReadScalerUnitHandler implements TaskHandler {
    @Autowired
    CosemXmlService cosemXmlService;
    @Autowired
    TaskDAO taskDAO;
    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData deviceData, String actionResult) throws UDISTaskHandlerException {
        if (!(deviceData instanceof CosemData)) {
            throw new UDISTaskHandlerException(TaskHandlerErrorCode.DEVICE_DATA_TYPE_NOT_SUPPORT.toString());
        }

        CosemData cosemData = (CosemData) deviceData;
        Integer scale = Convert.toInt(cosemXmlService.getData(cosemData.getChildAt(0).getType(), cosemData.getChildAt(0).getValue()));
        Integer unitEnum = Convert.toInt(cosemXmlService.getData(cosemData.getChildAt(1).getType(), cosemData.getChildAt(1).getValue()));
        Unit unit = Unit.forValue(unitEnum);
        String scaleResult = String.format("(%s:%s)", unit.getText(), scale);
        if (task.getIsODR()) {
            Map<String, Object> m = JSONUtil.toBean(atomicTask.getAtomicTaskParam(), Map.class);
            taskDAO.addTaskData(task.getTaskNo(),  atomicTask.getAtomicTaskNo(), String.valueOf(m.get("dataItemId")), scaleResult, Long.valueOf(2 * 60 * 60), true);
        }
        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        String key = "message";
        if (atomicTask.getGroupId() == OperationGroup.ReadRegister.getId().intValue()) {
            Map<String, Object> m = JSONUtil.toBean(atomicTask.getAtomicTaskParam(), Map.class);
            key = m.get("dataItemId") != null ? Convert.toStr(m.get("dataItemId")) : key;
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), key, message, 3600l, false);
        }
        return -1;
    }
}